package com.core.initialize;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.util.Map;

import com.core.EnginService;
import com.core.action.HttpAction;
import com.core.rest.AbstractHttpHandler;

public class ServerHttpHandler extends SimpleChannelInboundHandler<Object>
{
	
	protected EnginService service;
	
	private Map<String,AbstractHttpHandler> handlers;
	
	private AbstractHttpHandler handler;
	
	private AbstractHttpHandler copiedHandler;
	
	private HttpMethod method;
	
	private HttpRequest httpRequest;
	
	public ServerHttpHandler(Map<String,AbstractHttpHandler> handlers){
	    
	    this.handlers = handlers;
	    
	}
	
	
	//public  AttributeKey<HttpRequest> httpRequest = new AttributeKey<HttpRequest>("httpRequest");
	
	public void setEnginService(EnginService service)
	{
		this.service = service;
	}
	
	private void process(Object msg,ChannelHandlerContext ctx) throws Exception{
	    
	    //controller = new HttpController();
	    
	    if (msg instanceof HttpRequest){
	        
	        HttpRequest request = (HttpRequest) msg;
	        
	        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
	        
	        String path = queryStringDecoder.path();
	        
	        //handler = controller.getHandler(path);
	        
	        handler = handlers.get(path);
	        
	        copiedHandler = handler.deepCopy();
	        
	        method = request.getMethod();
            
            httpRequest = request;
	        
	    }
	    
	    if (msg instanceof HttpContent){
	    	this.service.getExecutor().pushAction(new HttpAction(copiedHandler, msg, ctx, method, httpRequest));
	    }
	    
	}
	
//	private void dealHttp(Object msg,ChannelHandlerContext ctx) throws Exception
//	{
//       if (msg instanceof HttpRequest)
//       {
//           HttpRequest request = (HttpRequest) msg;
//           Attribute<HttpRequest> attr = ctx.attr(httpRequest);
//           attr.set(request);
////           List<Map.Entry<String, String>> headers = request.headers().entries();
////           if (!headers.isEmpty()) {
////               for (Map.Entry<String, String> h: request.headers().entries()) {
////                   String key = h.getKey();
////                   String value = h.getValue();
////                   System.out.println(key);
////                   System.out.println(value);
////               }
////           }
//           QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
//           Map<String, List<String>> params = queryStringDecoder.parameters();
//           if (!params.isEmpty()) {
//               for (Entry<String, List<String>> p: params.entrySet()) {
//                   String key = p.getKey();
//                   List<String> vals = p.getValue();
//                   for (String val : vals) {
//                   	System.out.println(val);
//                   }
//               }
//           }
//       }
//
//       if (msg instanceof HttpContent) {
//           HttpContent httpContent = (HttpContent) msg;
//           ByteBuf content = httpContent.content();
//           if (content.isReadable()) {
//               System.out.println(content.toString(CharsetUtil.UTF_8));
//           }
//           
//           
//           String responseContent = new String("吃饭了");
//           
//           byte[] bytes = responseContent.getBytes(CharsetUtil.UTF_8);
//           ByteBuf buf = Unpooled.buffer(bytes.length);
//           buf.writeBytes(bytes);
//           
//           
//           FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);
//           response.headers().set(CONTENT_TYPE, "text/plain");
//           response.headers().set(CONTENT_LENGTH, bytes.length);
//
//           Attribute<HttpRequest> attr = ctx.attr(httpRequest);
//           HttpRequest request = attr.get();
//           
//           boolean keepAlive = isKeepAlive(request);
//           
//           
//           if (!keepAlive) {
//               ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
//           } else {
//               response.headers().set(CONNECTION, Values.KEEP_ALIVE);
//               ctx.writeAndFlush(response);
//           }
//       }
//	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		try {
			//dealHttp(msg,ctx);
		    
		    process(msg,ctx);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
